package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
public class VendoutResultHandler implements MsgHandler {
    @Autowired
    private VendoutRunningService vendoutRunningService;

    @Autowired
    private ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VendoutResultContract vendoutResultContract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        VendoutData vendoutData = vendoutResultContract.getVendoutData();
        if (vendoutResultContract.isSuccess()) {
            vendRuningUpdate(vendoutData);
        } else {
            rollbackCannel(vendoutResultContract, vendoutData);
        }

    }

    private void vendRuningUpdate(VendoutData vendoutData) {
        String orderNo = vendoutData.getOrderNo();
        VendoutRunningEntity vendoutRunningEntity = vendoutRunningService.getOne(new LambdaQueryWrapper<VendoutRunningEntity>().eq(VendoutRunningEntity::getOrderNo, orderNo));
        vendoutRunningEntity.setStatus(true);
        vendoutRunningService.updateById(vendoutRunningEntity);
    }

    private void rollbackCannel(VendoutResultContract vendoutResultContract, VendoutData vendoutData) {
        String channelCode = vendoutData.getChannelCode();
        ChannelEntity channelInfo = channelService.getChannelInfo(vendoutResultContract.getInnerCode(), channelCode);
        channelInfo.setCurrentCapacity(channelInfo.getCurrentCapacity()+1);
        channelService.updateById(channelInfo);
    }
}
